Page({
  data: {
    devices: [],
    filteredDevices: [],
    showModal: false,
    filterEmptyName: true,
    tempFilterEmptyName: false,
    rssiThreshold: -120,
    tempRssiThreshold: -120
  },
  onLoad() {
    // 页面加载时自动申请蓝牙权限
    this.requestBluetoothPermission();
  },
  /**
   * 申请蓝牙权限
   */
  requestBluetoothPermission() {
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('蓝牙适配器初始化成功', res);
        wx.showToast({
          title: '蓝牙权限已开启',
          icon: 'success'
        });
        // 蓝牙权限获取成功后，自动开启蓝牙设备搜索
        this.startBluetoothDeviceDiscovery();
      },
      fail: (err) => {
        console.error('蓝牙适配器初始化失败', err);
        wx.showToast({
          title: '蓝牙权限开启失败',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 重新搜索蓝牙设备
   */
  restartBluetoothDeviceDiscovery() {
    // 清除已搜索到的设备信息
    this.setData({
      devices: [],
      filteredDevices: []
    });
    // 停止当前的搜索（如果正在进行）
    wx.stopBluetoothDevicesDiscovery({
      success: () => {
        // 重新开启搜索
        this.startBluetoothDeviceDiscovery();
      },
      fail: (err) => {
        console.error('停止搜索蓝牙设备失败', err);
        // 即使停止失败，也尝试重新开启搜索
        this.startBluetoothDeviceDiscovery();
      }
    });
  },

  /**
   * 开始搜索蓝牙设备
   */
  startBluetoothDeviceDiscovery() {
    wx.startBluetoothDevicesDiscovery({
      services: [],
      success: (res) => {
        console.log('开始搜索蓝牙设备', res);
        wx.showToast({
          title: '开始搜索蓝牙设备',
          icon: 'success'
        });
        wx.onBluetoothDeviceFound((res) => {
          const newDevices = res.devices;
          newDevices.forEach((newDevice) => {
            const existingDeviceIndex = this.data.devices.findIndex((device) => device.deviceId === newDevice.deviceId);
            if (existingDeviceIndex > -1) {
              // 如果设备已存在，更新其 RSSI
              const updatedDevices = [...this.data.devices];
              updatedDevices[existingDeviceIndex].RSSI = newDevice.RSSI;
              this.setData({
                devices: updatedDevices
              }, () => {
                // 更新过滤后的设备列表
                this.applyFilter(); 
              });
            } else {
              // 如果设备是新发现的，添加到设备列表
              this.setData({
                devices: [...this.data.devices, newDevice]
              }, () => {
                // 更新过滤后的设备列表
                this.applyFilter(); 
              });
            }
          });
        });
      },
      fail: (err) => {
        console.error('搜索蓝牙设备失败', err);
        wx.showToast({
          title: '搜索蓝牙设备失败',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 显示过滤设置弹窗
   */
  showFilterModal() {
    this.setData({
      showModal: true,
      tempFilterEmptyName: this.data.filterEmptyName,
      tempRssiThreshold: this.data.rssiThreshold
    });
  },

  /**
   * 隐藏过滤设置弹窗
   */
  hideFilterModal() {
    this.setData({
      showModal: false,
      filterEmptyName: this.data.tempFilterEmptyName,
      rssiThreshold: this.data.tempRssiThreshold
    }, () => {
      this.applyFilter();
    });
  },

  /**
   * 处理过滤选项改变
   */
  handleFilterChange(e) {
    const filterValue = e.detail.value.includes('filterEmptyName');
    this.setData({
      tempFilterEmptyName: filterValue
    });
  },

  /**
   * 处理信号强度阈值改变（滑动结束）
   */
  handleRssiThresholdChange(e) {
    const threshold = e.detail.value;
    this.setData({
      tempRssiThreshold: threshold
    });
  },

  /**
   * 处理信号强度阈值实时变化（滑动中）
   */
  handleRssiThresholdChanging(e) {
    const threshold = e.detail.value;
    this.setData({
      tempRssiThreshold: threshold
    });
  },

  /**
   * 应用过滤规则
   */
  applyFilter() {
    let filtered = this.data.devices;
    if (this.data.filterEmptyName) {
      filtered = filtered.filter(device => device.name);
    }
    if (this.data.rssiThreshold > -120) {
      filtered = filtered.filter(device => device.RSSI >= this.data.rssiThreshold);
    }
    this.setData({
      filteredDevices: filtered
    });
  }, // 这里添加了逗号
  connectToDevice: function (e) {
    const deviceId = e.currentTarget.dataset.deviceid;
    wx.navigateTo({
      url: `/pages/connect/connect?deviceId=${deviceId}`
    });
  }
});